import { useActiveObject } from '@renderer/stores/activeObject'
import { useViewportStore } from '@renderer/stores/viewport'
import { storeToRefs } from 'pinia'
import { Vector2 } from 'three'
import { OutlinePass, RenderPass, SMAAPass } from 'three/examples/jsm/Addons'
import { watch } from 'vue'

export default function () {
  const activeObjectStore = useActiveObject()
  const { activeShallowRef } = storeToRefs(activeObjectStore)

  const viewportStore = useViewportStore()
  const { composer, scene, camera, canvas } = storeToRefs(viewportStore)

  if (canvas.value && composer.value && scene.value && camera.value) {
    const { clientWidth, clientHeight } = canvas.value
    const renderPass = new RenderPass(scene.value, camera.value)
    composer.value.addPass(renderPass)
    // 抗锯齿
    const smaaPass = new SMAAPass(window.innerWidth, window.innerHeight)
    composer.value.addPass(smaaPass)

    const outlinePass = new OutlinePass(
      new Vector2(clientWidth, clientHeight),
      scene.value,
      camera.value
    )
    outlinePass.visibleEdgeColor.set(0xffffff)
    outlinePass.edgeThickness = 2
    outlinePass.edgeStrength = 10
    composer.value.addPass(outlinePass)

    watch(
      () => activeShallowRef.value,
      (obj) => {
        if (obj) {
          scene.value?.traverse((node) => {
            if (node.uuid === obj.uuid) {
              outlinePass.selectedObjects = [node]
            }
          })
        } else {
          outlinePass.selectedObjects = []
        }
      }
    )
  }
}
